package com.power.filter;

import com.power.common.Contants;
import com.power.ov.ResultData;
import com.power.utils.WriterUtil;
import com.sun.deploy.net.HttpRequest;
import com.sun.deploy.net.HttpResponse;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 朱雄
 * Date: 2020/10/06 20:12
 * Description:过滤器
 * Version: V1.0
 */
public class RoleFilter implements Filter{


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        HttpSession session=request.getSession();
        Object object=  session.getAttribute("user");
        List<Map<String, Object>> list= (List<Map<String, Object>>) object;
        //得到请求路径
        String path=request.getServletPath();
        if ("/login.do".equals(path)){
            filterChain.doFilter(request, response);
        }
        boolean flag=false;
        if (list !=null){
            for (Map map:list) {
                //找到角色所对应的路径
                String permission_name=map.get("permission_name").toString();
                    if (path.equals(permission_name)){
                        flag=true;
                        break;
                    }
        }
        if (flag){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            ResultData resultData=new ResultData();
            resultData.setCode(Contants.NO_ROlE);
            resultData.setMsg("权限不足");
            WriterUtil.getWriter(response,resultData);
        }
        }
    }

    @Override
    public void destroy() {

    }
}
